package com.kyw.androidquicklib.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.view.View;

import com.kyw.androidquicklib.R;
import com.kyw.androidquicklib.util.DimenUtil;

import androidx.annotation.Nullable;

public class MessageToastView extends View {
    public MessageToastView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }
    int cRadius = 0;
    int viewWidth;
    int viewHeight;
    int textMargin;
    String msgNumber = "0";
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        viewWidth = getMeasuredWidth();
        viewHeight = getMeasuredHeight();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        textMargin = DimenUtil.dip2px(getContext(),2);

        Paint paint=new Paint();
        paint.setColor(Color.RED);
        paint.setStyle(Paint.Style.FILL);
        paint.setAntiAlias(true);

        //让圆的高度相对于控件的1/3
        cRadius = viewHeight/6;
        int cX = viewWidth-cRadius;
        int cY = cRadius;
        canvas.drawCircle(cX,cY,cRadius,paint);
        paint.setColor(Color.WHITE);

        //绘制消息数字
        String writeText = msgNumber;
        Rect rect = new Rect();
        int textSize = 10;
        while (true){
            paint.setTextSize(textSize);
            paint.getTextBounds(writeText, 0, writeText.length(), rect);
            int textWidth = rect.width();
            int textHeight = rect.height();
            if(writeText.length() == 1){
                if(textHeight > cRadius*2 - textMargin*2){
                    break;
                }
            }else {
                if(textWidth > cRadius*2 - textMargin*2){
                    break;
                }
            }
            ++textSize;
        }
        paint.setTextSize(textSize-1);
        paint.getTextBounds(writeText, 0, writeText.length(), rect);
        int textWidth = rect.width();
        int textHeight= rect.height();
        int textX = cX - textWidth/2 - 1;
        int textY = cY + textHeight/2;
        canvas.drawText(writeText,textX,textY,paint);

    }
    public void setMsgNumber(int number){
        if(number > 99){
            msgNumber = "+99";
        }
        msgNumber = number + "";
        invalidate();
    }

}
